<?php

declare(strict_types=1);

namespace App\Controller\Backend;

use App\Utils\Helper\ControllerHelper;
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;

final class FeedbackAdminController extends ControllerHelper {

    protected function preShow (Request $request, $object) {
        // 更新阅读状态
        if (!$object->getStatus()) {
            $object->setStatus(true);
            $this->getDoctrine()->getManager()->flush();
        }

        return null;
    }

    /**
     * 批量已读
     * @param ProxyQueryInterface $query
     * @param Request $request
     * @return RedirectResponse
     */
    public function batchActionRead (ProxyQueryInterface $query, Request $request) {
        if ($this->isAppModeDemo()) {
            $this->addFlash('sonata_flash_error', 'Demo模式下禁止批量已读数据');
            return $this->redirectToList();
        }

        $where = '';
        $alias = 'f';
        if ($request->get('all_elements')) {
            // 获取过滤条件
            $filter = [];
            $filterFields = $this->admin->getFilterFieldDescriptions();
            $filterParameters = $this->admin->getFilterParameters();
            foreach ($filterFields as $field => $filterField) {
                if (isset($filterParameters[$field]) && $filterParameters[$field]['value']) {
                    $buildWhereFunction = $filterField->getMappingType().'BuildWhere';
                    if (method_exists($this, $buildWhereFunction)) {
                        $buildResult = $this->$buildWhereFunction($alias, $filterField, $filterParameters[$field]['value']);
                        if ($buildResult) {
                            array_push($filter, $buildResult);
                        }
                    }
                }
            }
            if ($filter) {
                $where = 'WHERE '.implode(' and ', $filter);
            }
        } else {
            $ids = $request->get('idx', []);
            if (!$ids) {
                $this->addFlash('sonata_flash_info', '未选择需要操作的对象');
                return new RedirectResponse(
                    $this->admin->generateUrl('list', [
                        'filter' => $this->admin->getFilterParameters(),
                    ])
                );
            } else {
                $where = 'WHERE '.$alias.'.id IN ('.implode(",", $ids).')';
            }
        }

        try {
            $updateSql = $this->getDoctrine()->getManager()->createQuery('UPDATE App\Entity\Feedback '.$alias.' SET '.$alias.'.status = true '.$where);
            $updateSql->execute();
        } catch (\Exception $e) {
            $this->addFlash('sonata_flash_error', '批量已读操作有错误发生');
            return new RedirectResponse(
                $this->admin->generateUrl('list', [
                    'filter' => $this->admin->getFilterParameters(),
                ])
            );
        }

        $this->addFlash('sonata_flash_success', '所选择的数据已经被已读');

        return new RedirectResponse(
            $this->admin->generateUrl('list', [
                'filter' => $this->admin->getFilterParameters(),
            ])
        );
    }
}
